/*
* OctLabel.cpp
*
* Copyright(C) 2009, Лущик Павел aka nanoo
*
* This code is lisenced under the GPL version 2. For details see 
* LISENCE.txt
*/

#include"OctLabelStorage.h"
#include<cmath>
OctLabelStorage::OctLabelStorage(QWidget *parent): QWidget(parent)
{
	int i;
	label = new QLabel("0");
	layout = new QHBoxLayout();
	for(i=0;i<OCT_DIGITS;i++){
		m[i] = new OctLabel(this);
	}
	layout->setSpacing(0);
	layout->addStretch(1);
	layout->addWidget(label);
	for(i=OCT_DIGITS-1;i>=0;i--){
		layout->addWidget(m[i]);
	}
	layout->addStretch(1);
	setLayout(layout);
	
	for(i=0;i<OCT_DIGITS-1;i++){
		connect(m[i],SIGNAL(up()),m[i+1],SLOT(go_up()));
		connect(m[i],SIGNAL(down()),m[i+1],SLOT(go_down()));
	}
	//connect(m[OCT_DIGITS-1],SIGNAL(up()),m[0],SLOT(go_up()));
	//connect(m[OCT_DIGITS-1],SIGNAL(down()),m[0],SLOT(go_down()));
		
	for(i=0;i<OCT_DIGITS;i++){
		connect(m[i],SIGNAL(wheel_is_running()),this,SLOT(generateValue_and_Emit_valueChanged()));
	}
	setValue(0);
	state=0;
}

void OctLabelStorage::setValue(int a)
{
	while(a<0)
		a+=0xffffff;
		
	while(a>0xffffff)
		a-=0xffffff;
	
	int i,ret=0;
	for(i=OCT_DIGITS-1;i>=0;i--){
		m[i]->setValue((floor(a/pow(010,i))));
		a = a % (int)pow(010,i);
	}
	for(i=0;i<OCT_DIGITS;i++){
		ret+=(m[i]->value())*pow(010,i);
	}
	if(ret!=state)
		generateValue_and_Emit_valueChanged();
	state=ret;
}

void OctLabelStorage::generateValue_and_Emit_valueChanged()
{
	int ret=0,i;
	for(i=0;i<OCT_DIGITS;i++){
		ret+=(m[i]->value())*pow(010,i);
	}
	state=ret;
	emit valueChanged(ret);
}
